'use strict'
const fs = require('fs')
const path = require('path')
const jwt = require('jsonwebtoken') //引入jsonwebtoken
const Service = require('egg').Service;
const Md5 = require('js-md5') 

class LoginService extends Service {
  async index (val){
    const { ctx,Service } = this;
    let acceptPass = Md5(val.passWord); 
    let data = await this.app.mysql.get('user',{ phone:val.phone});
    this.checkSuccess(data); 
    if(data){
      if(acceptPass === data.passWord){
        const usersData = {
          corpid:1,
          userid:data.id,
        }
        const token = ctx.helper.loginToken({ corpid: usersData.corpid, userid: usersData.userid }, this.app.config.timeStamp) // token生成
        await this.app.redis.set(usersData.corpid+usersData.userid, token, 'ex', this.app.config.timeStamp) // 保存到redis
        
        //保存到客户端浏览器的cookie中
        ctx.cookies.set('token', token,{
          maxAge: this.app.config.timeStamp,
          path: '/',
          domain: 'localhost',
          httpOnly: false,
        });
        return {
          token,
          expiration_time:this.app.config.timeStamp,
        };
      }else{
        return null;
      }
    }
  }
async Info(val){
  //token解密获取用户id
  let userid = this.verifyToken(val.token).userid;
  let data = await this.app.mysql.get('user',{id:userid});
  this.checkSuccess(data);
  if(data!==null){
    delete data.passWord;
    delete data.id;
  }
  return data;
}
  // 封装统一的调用检查函数，可以在查询、创建和更新等 Service 中复用
  checkSuccess(result) {
    if(result!==null){
      if ( result.errno && result.code) {
        const errorMsg = result && result.error_msg ? result.error_msg : 'unknown error';
        this.ctx.throw(result, errorMsg,result);
      }else{
        return result;
      }
    }else{
      return result;
    }
  }
  // 解密，验证
  verifyToken(token) {
  const cert = fs.readFileSync(path.join(__dirname, '../../public/rsa_public_key.pem')) // 公钥，看后面生成方法
  let res = ''
  try {
    const result = jwt.verify(token, cert, { algorithms: [ 'RS256' ] }) || {}
    const { exp } = result,
      current = Math.floor(Date.now() / 1000)
    if (current <= exp) res = result.data || {}
  } catch (e) {
    console.log(e)
  }
  return res
}
}
module.exports = LoginService;